<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>分类管理</el-breadcrumb-item>
      <el-breadcrumb-item>新建分类</el-breadcrumb-item>
    </el-breadcrumb>

    <el-form label-position="right" label-width="100px">
      <el-form-item label="所属分类">
        <el-select v-model="model.categories" placeholder="请选择">
          <el-option
            v-for="item in categoryOptionList"
            :key="item._id"
            :label="item.name"
            :value="item._id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="分类名称">
        <el-input class="wid" v-model="model.name"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="warning" style="margin-left:150px" @click="save">确定</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  name: 'CategoryCreate',
  data() {
    return {
      model: {
        name: '',
        parent: null
      },
      categoryOptionList: []
    }
  },
  methods: {
    async save() {
      const result = await this.$http.post(`rest/categories`, this.model)
      if (result.status !== 200) {
        return this.$message.error('创建分类失败')
      }
      this.$message.success(`成功创建分类：${result.data.name}`)
      this.$router.push('/categories/list')
    },
    async getCategoryOptionsList() {
      const res = await this.$http.get(`rest/categories`)
      this.categoryOptionList = res.data.filter(item => {
        if (!item.parent) {
          return true
        } else {
          return false
        }
      })
    }
  },
  created() {
    this.getCategoryOptionsList()
  }
}
</script>

<style scoped>
.wid {
  width: 40%;
}
.el-form {
  margin-top: 20px;
}
</style>